package com.libreaccess.reporting.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Time;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import com.libredigital.reporting.schema.CompletedReport;
import com.libredigital.reporting.schema.Parameter;
import com.libredigital.reporting.schema.ParametersList;
import com.libredigital.reporting.schema.ReportDS;
import com.liferay.portal.model.User;
public final class JasperUtils {

	static final Logger logger = new Logger(JasperUtils.class);
	
	static DataSource ds;
	
	public static List<CompletedReport> GetFilesInDirectory(File folder) {
		List<CompletedReport> cmpRep = new ArrayList<CompletedReport>(); 
		if (folder.isDirectory())
		{
			CompletedReport r;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			for (File f: folder.listFiles()) {
				if (f.isFile()) {
					String extOnly = f.getName().substring(f.getName().lastIndexOf('.')+1);
						
					r = new CompletedReport();
					String name = f.getName().substring(0,f.getName().lastIndexOf('.'));
					String reportName =f.getName().substring(0,f.getName().lastIndexOf('_'));
					if (name.indexOf(".")>0)
					{
						reportName = name.substring(name.lastIndexOf('.')+1);
						name = name.substring(0, name.lastIndexOf('.'));
					}
					r.setName(name);
					r.setReportName(reportName);
					r.setTimeCreated(sdf.format(new java.util.Date(f.lastModified())));
					r.setType(extOnly);
					r.setMyReportName(name.indexOf("_")>0 ? name.substring(0,name.lastIndexOf('_')):name);	
                    cmpRep.add(r);
				}
			}
		}
		else
		{
			logger.warn(folder.getName() + " is not a folder");
		}
		return cmpRep;
	}

	public static Connection getReportViewConnection(ReportDS ds) throws SQLException
	{
		Connection conn = null;
	    try {
		       Class.forName(ds.getJdbcDriver()).newInstance();
		    }
		    catch (Exception ex){
		       logger.debug("Check classpath. Cannot load db driver: " + ds.getJdbcDriver());
		    }

		    try {
		      conn = DriverManager.getConnection(ds.getJdbcUrl(), ds.getUserName(), ds.getPassword());
		    }
		    catch (SQLException e){
		       logger.error( "Driver loaded, but cannot connect to db: " + ds.getJdbcUrl());
		       logger.error("SQLException:"+e.getMessage());
		    }
		return conn;
	}
	
	public static void setDataSource(DataSource d) {
		if (d!=null) {
			ds = d;
		}
	}
	
	public static DataSource getDataSource() {
		if (ds== null) {
		InitialContext context;
		try {
			context = new InitialContext();
			ds = (DataSource) context.lookup("java:/jdbc/ReportingDS");
		} catch (NamingException e) {
			e.printStackTrace();
			logger.error("Cannot lookup datasource: "+ e.getMessage());
		  }
		}
		return ds;
	}
	
	public static byte[] putReportUtilToArray(ReportUtil ru)
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oout;
		try {
			oout = new ObjectOutputStream(baos);
			oout.writeObject(ru);
			oout.close();
		} catch (IOException e) {
			logger.error("IOException:"+e.getMessage());
		}
		return baos.toByteArray();
	}

	public static Date getParsedDate(String str, Date nextTimeFired) {
		Calendar d = Calendar.getInstance();
		d.setTime(nextTimeFired);
		logger.debug("date:"+d.getTime());
		String params[] = str.split("_");
		int type = Integer.parseInt(params[0]);
		int period = Integer.parseInt(params[1]);
		logger.debug("Type (Date-1/Week-2/Month-3):"+type);
		logger.debug("Period ago:"+period);
		d.add(Calendar.DATE, -period);
		logger.debug("modified date:"+d.getTime());
		return d.getTime();
	}
	
	public static ArrayList<UserLiferay> fillRecipients(List<User> allLiferayUsers, String email) {
		ArrayList<UserLiferay> res = new ArrayList<UserLiferay>();
		UserLiferay usLFR;
		if (email == null) email = "";
		String[] emails = email.split(";");
		for (String em: emails) {
			for (User u: allLiferayUsers)
			{
				if (em.trim().toUpperCase().equalsIgnoreCase(u.getEmailAddress().trim().toUpperCase())) {
					usLFR = new UserLiferay();
					usLFR.setEmail(u.getEmailAddress());
					usLFR.setName(u.getFullName());
					usLFR.setUserId(u.getUserId());
					res.add(usLFR);
					logger.debug("User:"+usLFR.getName()+" "+ usLFR.getEmail() + " was recognized and added as recipient");
				}
			}
		}
		return res;
	}
	
	public static ReportingPortletDataPerUser setupParameters(ReportingPortletDataPerUser sessionData) {
		HashMap<String, Object> model = new HashMap<String, Object>();
		DateFormat formatterDate = new SimpleDateFormat("MM/dd/yyyy");
		DateFormat fomatterHours = new SimpleDateFormat("HH:mm");
		DateFormat fomatterTime = new SimpleDateFormat("MM/dd/yyyy HH:mm");
		Date nextDateFired;
		if (sessionData.getReportUtil()!= null && sessionData.getReportUtil().getTriggerExpr() != null && sessionData.getReportUtil().getTriggerExpr().getNextFireTime()!= null && !sessionData.getReportUtil().getTriggerExpr().getNextFireTime().equals(new Date(0))) {
			Calendar cal = Calendar.getInstance();
			nextDateFired = sessionData.getReportUtil().getTriggerExpr().getNextFireTime();
			cal.setTime(nextDateFired);
			if (sessionData.getReportUtil().getSchedulerStartDate()!=null)
			{
				Calendar calSchedulerStartDate = Calendar.getInstance();
				calSchedulerStartDate.setTime(sessionData.getReportUtil().getSchedulerStartDate());
				cal.set(Calendar.HOUR_OF_DAY, calSchedulerStartDate.get(Calendar.HOUR_OF_DAY));
				cal.set(Calendar.MINUTE, calSchedulerStartDate.get(Calendar.MINUTE));
				cal.set(Calendar.SECOND, calSchedulerStartDate.get(Calendar.SECOND));
				nextDateFired = cal.getTime();
			}
		}
		else
		{
			nextDateFired = new Date();
		}
		logger.debug("NextDateFired = "+ fomatterTime.format(nextDateFired));
		ArrayList<Object> prms = new ArrayList<Object>();
		String parameters = "";
		Boolean isValid = true;
		NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
		String shortClassName;
		ArrayList<String> valList;
		for (JRParameter p : sessionData.getDesign().getParameters()) {
			if (!p.isSystemDefined() && p.isForPrompting()) {
				prms.add(p);
				shortClassName = p.getValueClassName().toString();
				shortClassName = shortClassName.substring(
						shortClassName.lastIndexOf('.') + 1).toLowerCase();
					try {
						switch (ReportingEnums.ParameterType.valueOf("_"	+ shortClassName)) {
						case _boolean:
							logger.debug("boolean parameter:" + !SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())));
							model.put(p.getName(), !SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())));
							parameters += p.getName()+ ":" + !SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())) + " ";
							break;
						case _byte:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								logger.debug("byte parameter:" + java.lang.Byte.parseByte(sessionData.getReportUtil().getParameters().get(p.getName())));
								model.put(p.getName(), java.lang.Byte.parseByte(sessionData.getReportUtil().getParameters().get(p.getName())));
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";
							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("byte parameter(default):" + p.getDefaultValueExpression().getText());
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("byte parameter(empty): 0 "); 
									model.put(p.getName(), java.lang.Byte.parseByte("0"));
									parameters += p.getName() + "(empty):0 ";
								}
							}
							break;
						case _date:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								try {
									logger.debug("date parameter:'"+p.getName()+"': " + formatterDate.parse(sessionData.getReportUtil().getParameters().get(p.getName()))); 
									model.put(p.getName(), formatterDate.parse(sessionData.getReportUtil().getParameters().get(p.getName())));
									parameters += p.getName() + ":" + formatterDate.parse(sessionData.getReportUtil().getParameters().get(p.getName())) + " ";
								}
								catch (ParseException ex) {
									logger.debug("date parameter(coded):'"+p.getName()+"': " + sessionData.getReportUtil().getParameters().get(p.getName()));
									model.put(p.getName(), getParsedDate(sessionData.getReportUtil().getParameters().get(p.getName()),nextDateFired));
									parameters += p.getName() +  " (coded):" + sessionData.getReportUtil().getParameters().get(p.getName())+" ";		
								}
							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("date parameter(default):" + p.getDefaultValueExpression().getText()); 
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("date parameter(empty): "+new java.util.Date()); 
									model.put(p.getName(), new java.util.Date());
									parameters += p.getName() + "(empty):"+ new java.util.Date()+" ";
								}
							}
							break;
						case _time:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								Time time = new Time(fomatterHours.parse(sessionData.getReportUtil().getParameters().get(p.getName())).getTime());
								logger.debug("time parameter:" + time); 
								model.put(p.getName(), time);
								parameters += p.getName() + ":" + time + " ";							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("time parameter(default):" + p.getDefaultValueExpression().getText()); 
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("time parameter(empty): "+new Time(0l)); 
									model.put(p.getName(), new Time(0l));
									parameters += p.getName() + "(empty):"+ new Time(0l)+" ";
								}
							}
							break;
						case _float:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								logger.debug("float parameter:"	+ java.lang.Float.parseFloat(sessionData.getReportUtil().getParameters().get(p.getName()))); 
								model.put(p.getName(), java.lang.Float.parseFloat(sessionData.getReportUtil().getParameters().get(p.getName())));
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";
							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("float parameter(default):" + p.getDefaultValueExpression().getText()); 
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("float parameter(empty): 0 "); 
									model.put(p.getName(), java.lang.Float.parseFloat("0"));
									parameters += p.getName() + "(empty):0 ";
								}
							}
							break;
						case _integer:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								logger.debug("integer parameter:" + java.lang.Integer.parseInt(sessionData.getReportUtil().getParameters().get(p.getName())));
								model.put(p.getName(), java.lang.Integer.parseInt(sessionData.getReportUtil().getParameters().get(p.getName())));
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";
							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("integer parameter(default):" + p.getDefaultValueExpression().getText()); 
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("integer parameter(empty): 0 ");
									model.put(p.getName(), java.lang.Integer.parseInt("0"));
									parameters += p.getName() + "(empty):0 ";
								}
							}
							break;
						case _long:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								logger.debug("long parameter:" + java.lang.Long.parseLong(sessionData.getReportUtil().getParameters().get(p.getName())));
								model.put(p.getName(), java.lang.Long.parseLong(sessionData.getReportUtil().getParameters().get(p.getName())));
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("long parameter(default):" + p.getDefaultValueExpression().getText()); 
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("long parameter(empty): 0 ");
									model.put(p.getName(), java.lang.Long.parseLong("0"));
									parameters += p.getName() + "(empty):0 ";
								}
							}
							break;
						case _number:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								logger.debug("number parameter:" + nf.parse(sessionData.getReportUtil().getParameters().get(p.getName()))); 
								model.put(p.getName(), nf.parse(sessionData.getReportUtil().getParameters().get(p.getName()))); 
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("number parameter(default):" + p.getDefaultValueExpression().getText()); 
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("number parameter(empty): 0 "); 
									model.put(p.getName(), nf.parse("0"));
									parameters += p.getName() + "(empty):0 ";
								}
							}
							break;
						case _short:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								logger.debug("short parameter:" + java.lang.Short.parseShort(sessionData.getReportUtil().getParameters().get(p.getName()))); 
								model.put(p.getName(), java.lang.Short.parseShort(sessionData.getReportUtil().getParameters().get(p.getName())));
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("short parameter(default):" + p.getDefaultValueExpression().getText()); 
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("short parameter(empty): 0 "); 
									model.put(p.getName(), java.lang.Short.parseShort("0"));
									parameters += p.getName() + "(empty):0 ";
								}
							}
							break;
						case _string:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								logger.debug("string parameter:" + sessionData.getReportUtil().getParameters().get(p.getName()));
								model.put(p.getName(), sessionData.getReportUtil().getParameters().get(p.getName()));
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";
							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("string parameter(default):" + p.getDefaultValueExpression().getText());
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("string parameter(empty): '' ");
									model.put(p.getName(), "");
									parameters += p.getName() + "(empty): ''";
								}
							}
							break;
						case _double:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								logger.debug("double parameter:" + java.lang.Double.parseDouble(sessionData.getReportUtil().getParameters().get(p.getName())));
								model.put(p.getName(), java.lang.Double.parseDouble(sessionData.getReportUtil().getParameters().get(p.getName())));
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("double parameter(default):" + p.getDefaultValueExpression().getText());
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("double parameter(empty): 0 ");
									model.put(p.getName(), java.lang.Double.parseDouble("0"));
									parameters += p.getName() + "(empty):0 ";
								}
							}
							break;
						case _bigdecimal:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								java.math.BigDecimal val = new java.math.BigDecimal(sessionData.getReportUtil().getParameters().get(p.getName()));
								logger.debug("big decimal parameter:" + val);
								model.put(p.getName(), val);
								parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("big decimal parameter(default):" + p.getDefaultValueExpression().getText());
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("big decimal parameter(empty): 0 ");
									model.put(p.getName(), new java.math.BigDecimal("0"));
									parameters += p.getName() + "(empty):0 ";
								}
							}
							break;
						case _list:
							logger.debug("List parameter:" + sessionData.getReportUtil().getParameters().get(p.getName()));
							valList = new ArrayList<String>();
							for (String s : sessionData.getReportUtil().getParameters().get(p.getName()).split(",")) {
								valList.add(s);
								parameters += p.getName() + ":" + s + " ";
							}
							model.put(p.getName(), valList);
							break;
						case _object:
							logger.debug("Object parameter:" + (java.lang.Object) (sessionData.getReportUtil().getParameters().get(p.getName())));
							model.put(p.getName(), (java.lang.Object) (sessionData.getReportUtil().getParameters().get(p.getName())));
							parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";
							break;
						case _timestamp:
							if (!SimpleUtils.isStringEmpty(sessionData.getReportUtil().getParameters().get(p.getName())))
							{
								try {
									java.sql.Timestamp timestamp = new java.sql.Timestamp(fomatterTime.parse(sessionData.getReportUtil().getParameters().get(p.getName())).getTime());
									logger.debug("timestamp parameter:" + timestamp);
									model.put(p.getName(), timestamp);
									parameters += p.getName() + ":" + timestamp + " ";
								}
								catch (ParseException ex) {
									logger.debug("timestamp parameter:" + sessionData.getReportUtil().getParameters().get(p.getName()));
									model.put(p.getName(), new java.sql.Timestamp(getParsedDate(sessionData.getReportUtil().getParameters().get(p.getName()),nextDateFired).getTime()));
									parameters += p.getName() + ":" + sessionData.getReportUtil().getParameters().get(p.getName()) + " ";	
								}
							}
							else
							{
								//any data push to model (will be used default value
								if (p.getDefaultValueExpression() != null) 
								{
									logger.debug("timestamp parameter(default):" + p.getDefaultValueExpression().getText());
									parameters += p.getName() + "(default):" + p.getDefaultValueExpression().getText() + " ";
								}
								else
								{
									logger.debug("timestamp parameter(empty): "+new java.sql.Timestamp(0l));
									model.put(p.getName(), new java.sql.Timestamp(0l));
									parameters += p.getName() + "(empty):"+ new java.sql.Timestamp(0l)+" ";
								}
							}
							break;
						case _collection:
						case _inputstream:
						case _jremptydataSource:
							break;
						}
					} catch (Exception e) {
						isValid = false;
						logger.debug("parameter:"+p.getName()+" value:"+sessionData.getReportUtil().getParameters().get(p.getName()));
						logger.error("incorrect cast");
						logger.error("Exception:"+e.getMessage());
					}
			}
		}
		sessionData.setModel(isValid? model:null);
		sessionData.setParameters(isValid? parameters:null);
		return sessionData;
	}

	public static JasperDesign loadReport(byte[] bytes)
			throws UnsupportedEncodingException, JRException {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		JasperDesign design = JRXmlLoader.load(bais);
		return design;
	}

	public static void copy(File fromFile, File toFile) throws IOException {
		FileInputStream from = null;
		FileOutputStream to = null;
		try {
			from = new FileInputStream(fromFile);
			to = new FileOutputStream(toFile);
			byte[] buffer = new byte[4096];
			int bytesRead;

			while ((bytesRead = from.read(buffer)) != -1)
				to.write(buffer, 0, bytesRead);
		} finally {
			if (from != null)
				from.close();
			if (to != null)
				to.close();
		}
	}

	public static byte[] getBytesFromFile(File file) throws IOException {
		InputStream is = new FileInputStream(file);
		long length = file.length();
		if (length > Integer.MAX_VALUE) { // File is too large
			throw new IOException("File is too large!");
		}

		byte[] bytes = new byte[(int) length];

		int offset = 0;
		int numRead = 0;
		try {
			while (offset < bytes.length
					&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}
		} catch (IOException e) {
			throw e;
		} finally {
			is.close();
		}

		if (offset < bytes.length) {
			throw new IOException("Could not completely read file "
					+ file.getName());
		}
		return bytes;
	}

	public static HashMap<String, Object> convertParametersToJasper(
			ParametersList list) {
		HashMap<String, Object> model = new HashMap<String, Object>();
		String shortClassName;
		NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
		DateFormat formatterDate = new SimpleDateFormat("MM/dd/yyyy");
		DateFormat fomatterHours = new SimpleDateFormat("hh:mm");
		DateFormat fomatterTime = new SimpleDateFormat("MM/dd/yyyy hh:mm");
		try {
			for (Parameter prm : list.getParameters()) {
				shortClassName = prm.getName().substring(
						prm.getName().lastIndexOf('.') + 1).toLowerCase();

				switch (ReportingEnums.ParameterType.valueOf("_" + shortClassName)) {
				case _boolean:
					logger.debug("boolean parameter:" + prm.getValue());

					model.put(prm.getName(), Boolean.parseBoolean(prm
							.getValue().toString()));
					break;
				case _byte:
					logger.debug("byte parameter:"
							+ java.lang.Byte.parseByte(prm.getValue()
									.toString()));
					model.put(prm.getName(), java.lang.Byte.parseByte(prm
							.getValue().toString()));
					break;
				case _date:
					logger.debug("date parameter:"
							+ formatterDate.parse(prm.getValue().toString()));
					model.put(prm.getName(), formatterDate.parse(prm.getValue()
							.toString()));
					break;
				case _time:
					Time time = new Time(fomatterHours.parse(
							prm.getValue().toString()).getTime());
					logger.debug("time parameter:" + time);
					model.put(prm.getName(), time);
					break;
				case _float:
					logger.debug("float parameter:"
							+ java.lang.Float.parseFloat(prm.getValue()
									.toString()));
					model.put(prm.getName(), java.lang.Float.parseFloat(prm
							.getValue().toString()));
					break;
				case _integer:
					logger.debug("integer parameter:"
							+ java.lang.Integer.parseInt(prm.getValue()
									.toString()));
					model.put(prm.getName(), java.lang.Integer.parseInt(prm
							.getValue().toString()));
					break;
				case _long:
					logger.debug("long parameter:"
							+ java.lang.Long.parseLong(prm.getValue()
									.toString()));
					model.put(prm.getName(), java.lang.Long.parseLong(prm
							.getValue().toString()));
					break;
				case _number:
					logger.debug("number parameter:"
							+ nf.parse(prm.getValue().toString()));
					model.put(prm.getName(), nf
							.parse(prm.getValue().toString()));
					break;
				case _short:
					logger.debug("short parameter:"
							+ java.lang.Short.parseShort(prm.getValue()
									.toString()));
					model.put(prm.getName(), java.lang.Short.parseShort(prm
							.getValue().toString()));
					break;
				case _string:
					logger
							.debug("string parameter:"
									+ prm.getValue().toString());
					model.put(prm.getName(), prm.getValue().toString());
					break;
				case _double:
					logger.debug("double parameter:"
							+ java.lang.Double.parseDouble(prm.getValue()
									.toString()));
					model.put(prm.getName(), java.lang.Double.parseDouble(prm
							.getValue().toString()));
					break;
				case _bigdecimal:
					java.math.BigDecimal val = new java.math.BigDecimal(
							java.lang.Double.parseDouble(prm.getValue()
									.toString()));
					logger.debug("big Decimal parameter:" + val);
					model.put(prm.getName(), val);
					break;
				case _list:
					logger.debug("List parameter:" + prm.getValue().toString());
					ArrayList<String> valList = new ArrayList<String>();
					for (String s : prm.getValue().toString().split(",")) {
						valList.add(s);
					}
					model.put(prm.getName(), valList);
					break;
				case _object:
					logger.debug("Object parameter:"
							+ (java.lang.Object) (prm.getValue().toString()));
					model.put(prm.getName(), (java.lang.Object) (prm.getValue()
							.toString()));
					break;
				case _timestamp:
					java.sql.Timestamp timestamp = new java.sql.Timestamp(
							fomatterTime.parse(prm.getValue().toString())
									.getTime());
					logger.debug("timestamp parameter:" + timestamp);
					model.put(prm.getName(), timestamp);
					break;
				case _collection:
				case _inputstream:
				case _jremptydataSource:
					break;
				}
			}
		} catch (Exception e) {
			logger.error("incorrect cast");
		}

		model.put(JRParameter.REPORT_FILE_RESOLVER, new CustomFileResolver(0L));
		return model;
	}

	public static ReportUtil GetReportUtilFromByteArray(byte[] mr)
	{
		ReportUtil rut = null;
		if (mr != null)
		{
			try {
				ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(mr));
				rut = (ReportUtil) objectIn.readObject();
			} catch (ClassNotFoundException e) {
				logger.error("ClassNotFoundException:"+e.getMessage());
				rut = null;
			} catch (IOException e) {
				logger.error("IOException:"+e.getMessage());
				rut = null;
			}	
		}
		return rut;
	}
}
